<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>订单管理</title>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Element-UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="../js/authChecker.js"></script>
    <style>
        /* 粉色主题 */
        .el-button--primary,
        .el-button--primary:hover,
        .el-button--primary:focus {
            background-color: #FF1493;
            border-color: #FF1493;
        }

        body {
            margin: 0;
            padding: 20px;
            background: #f2f2f2;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
        }

        .search-box {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .order-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }

        /* 批量切换状态按钮透明 */
        .el-button--warning {
            background-color: transparent !important;
            border-color: #E6A23C !important;
            color: #E6A23C !important;
        }

        /* 添加商品按钮透明 */
        .el-button--primary {
            background-color: transparent !important;
            border-color: #FF1493 !important;
            color: #FF1493 !important;
        }
        .el-button--primary1{
            background-color: transparent !important;
            border-color: #FF1493 !important;
            color: #FF1493 !important;
        }

        .el-button--warning:hover,
        .el-button--warning:focus {
            background-color: #FF1493;
            color: #fff;
        }

        .page-title {
            font-size: 22px;
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
        }

        /* 加载动画 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }

        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #FF1493;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        /* 消息提示 - 仿示例样式 */
        .message {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 10px 20px;
            border-radius: 4px;
            background-color: #f0f9eb;
            border: 1px solid #c2e7b0;
            color: #67c23a;
            z-index: 9999;
            display: none;
            align-items: center;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            opacity: 0;
        }

        /* 对勾图标样式 */
        .message i {
            font-family: "element-icons" !important;
            content: "\E652";
            margin-right: 8px;
            font-size: 16px;
            color: #67c23a;
        }

        /* 显示动画 */
        .message.show {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }

        /* 隐藏动画 */
        .message.hide {
            opacity: 0;
            transform: translateX(-50%) translateY(-20px);
        }

        /* 表格样式 */
        .el-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }

        .el-table th,
        .el-table td {
            padding: 12px 0;
            border: 1px solid #ebeef5;
            text-align: center;
        }

        .el-table th {
            background-color: #f5f7fa;
            color: #909399;
            font-weight: bold;
        }

        .el-table tr:hover {
            background-color: #f5f7fa;
        }

        .el-pagination {
            margin-top: 15px;
            text-align: right;
        }

        .el-pagination button {
            padding: 0 6px;
            margin: 0 5px;
            border: 1px solid #dcdfe6;
            background: #fff;
            border-radius: 4px;
            cursor: pointer;
        }

        .el-pagination button:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }

        .el-tag {
            padding: 0 10px;
            border-radius: 4px;
            font-size: 12px;
            line-height: 24px;
        }

        .el-tag--success {
            background-color: #f0f9eb;
            border-color: #e1f3d8;
            color: #e0ffdd;
        }

        .el-tag--info {
            background-color: #f4f4f5;
            border-color: #e9e9eb;
            color: #909399;
        }

        .el-tag--warning {
            background-color: #fdf6ec;
            border-color: #faecd8;
            color: #e6a23c;
        }

        /* 表单样式 */
        .el-form--inline .el-form-item {
            margin-right: 10px;
            margin-bottom: 0;
            vertical-align: top;
        }

        .el-form-item__label {
            padding: 0 12px 0 0;
            color: #606266;
            line-height: 40px;
        }

        .el-input__inner {
            width: 100%;
            padding: 8px 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            color: #606266;
            outline: none;
            height: 40px;
            line-height: 40px;
        }

        .el-select {
            display: inline-block;
            position: relative;
        }

        /* 搜索框样式 */
        .search-box {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        /* 自定义对话框样式 */
        .dialog-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 2000;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .dialog-container {
            width: 400px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .dialog-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ebeef5;
            font-size: 18px;
            color: #303133;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .dialog-close {
            font-size: 20px;
            color: #909399;
            cursor: pointer;
        }

        .dialog-close:hover {
            color: #FF1493;
        }

        .dialog-body {
            padding: 20px;
        }

        .dialog-footer {
            padding: 15px 20px;
            border-top: 1px solid #ebeef5;
            text-align: right;
        }

        /* 退款理由输入框样式 */
        /* 退款理由输入框样式 */
        #refuseReason {
            width: 100%;
            min-height: 80px;
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            resize: vertical; /* 允许垂直方向调整大小 */
            font-family: inherit;
            font-size: 14px;
            box-sizing: border-box; /* 让内边距和边框不影响宽度计算 */
            max-height: 120px; /* 限制最大高度，避免过高超出弹窗 */
        }

    </style>
</head>
<body>
<div class="page-title">订单管理</div>
<div id="app">
    <!-- 搜索区 -->
    <div class="search-box">
        <form class="el-form el-form--inline" id="searchForm" onsubmit="return false;">
            <div class="el-form-item">
                <label class="el-form-item__label">订单编号</label>
                <div class="el-form-item__content">
                    <input type="text" class="el-input__inner" id="ordernum" placeholder="请输入订单编号">
                </div>
            </div>

            <div class="el-form-item">
                <label class="el-form-item__label">客户名称</label>
                <div class="el-form-item__content">
                    <input type="text" class="el-input__inner" id="userName" placeholder="请输入客户名称">
                </div>
            </div>

            <div class="el-form-item">
                <label class="el-form-item__label">订单状态</label>
                <div class="el-form-item__content">
                    <select class="el-select__inner" id="orderstatus" style="width:110px;height:40px;">
                        <option value="">全部状态</option>
                        <option value="0">待支付</option>
                        <option value="1">待配送</option>
                        <option value="2">已完成</option>
                    </select>
                </div>
            </div>

            <div class="el-form-item">
                <div class="el-form-item__content">
                    <button type="button" class="el-button el-button--primary" onclick="handleSearch()"
                            style="background: transparent; color: #FF1493; border-color: #FF1493;">搜索</button>
                    <button type="button" class="el-button" onclick="resetSearch()"
                            style="color:#ff85a2;border-color:#ff85a2;">重置</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 表格 -->
    <table class="el-table" id="orderTable">
        <thead>
        <tr>
            <th style="width: 100px;">订单ID</th>
            <th style="width: 120px;">订单编号</th>
            <th style="width: 120px;">客户名称</th>
            <th style="width: 100px;">订单金额</th>
            <th style="width: 100px;">订单数量</th>
            <th style="width: 100px;">订单状态</th>
            <th style="width: 100px;">是否评价</th>
            <th style="width: 100px;">退款情况</th>
            <th style="width: 150px;">蛋糕名称</th>
            <th style="width: 100px;">下单时间</th>
            <th style="width: 100px;">退款原因</th>
            <th style="width: 100px;">商家回复</th>
        </tr>
        </thead>
        <tbody>
        <!-- 动态内容将通过JS填充 -->
        </tbody>
    </table>

    <div class="el-pagination">
        <button class="el-pagination__first" onclick="firstPage()" id="firstBtn">首页</button>
        <button class="el-pagination__prev" onclick="prevPage()" id="prevBtn">上一页</button>第
        <span class="el-pagination__current" id="currentPage"
              style="width: 10px; text-align: center; font-size: 20px; margin: -2px -4px -20px -10px;">1</span>页
        <button class="el-pagination__next" onclick="nextPage()" id="nextBtn">下一页</button>
        <button class="el-pagination__last" onclick="lastPage()" id="lastBtn">尾页</button>
        <span class="el-pagination__total">共 <span id="totalItems">0</span> 条</span>
    </div>
</div>

<!-- 加载动画 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>

<!-- 消息提示 -->
<div class="message" id="message"></div>

<!-- 退款确认对话框 -->
<!-- 退款确认对话框 -->
<div class="dialog-overlay" id="refundDialog">
    <div class="dialog-container">
        <div class="dialog-header">
            <span>确认退款操作</span>
            <span class="dialog-close" onclick="closeRefundDialog()">×</span>
        </div>
        <div class="dialog-body">
            <p>是否同意该订单退款？</p>
            <!-- 不同意退款理由输入框 -->
            <textarea id="refuseReason" placeholder="请输入不同意退款的理由" style="display: none; margin-top: 15px;"></textarea>
        </div>
        <div class="dialog-footer">
            <!-- 给同意退款按钮加id -->
            <button type="button" class="el-button el-button--primary" id="agreeRefundBtn" onclick="agreeRefund()">同意退款</button>
            <button type="button" class="el-button el-button--primary1" id="refuseBtn" onclick="toggleRefuseReason()">不同意退款</button>
        </div>
    </div>
</div>

<script>
    // 在页面加载时立即检查登录状态
    if (!checkAdminLogin()) {
        // 登录检查失败，阻止页面继续加载
        console.log('登录验证失败，已跳转至登录页');
    } else {
        // 全局变量
        let tableData = [];
        let currentPage = 1;
        let limit = 10;
        let total = 0;
        let currentRefundOrder = null;
        let isRefuseMode = false; // 标记是否处于不同意退款模式

        // 页面加载完成后初始化
        $(document).ready(function() {
            fetchData();
        });

        // 显示加载中
        function showLoading() {
            $('#loadingOverlay').css('display', 'flex');
        }

        // 隐藏加载中
        function hideLoading() {
            $('#loadingOverlay').hide();
        }

        // 获取订单状态文本
        function getOrderStatusText(status) {
            const statusMap = {
                '0': '待支付',
                '1': '待配送',
                '2': '待收货',
                '3': '已完成'
            };
            return statusMap[status] || '未知状态';
        }

        // 显示消息（带动画）
        function showMessage(type, message) {
            const msgElement = $('#message');
            msgElement.removeClass().addClass(`message message-${type}`);
            msgElement.text(message);

            // 先应用离开动画重置位置
            msgElement.removeClass('show').addClass('hide');
            setTimeout(() => {
                // 再切换进入动画
                msgElement.removeClass('hide').addClass('show');
                msgElement.show();

                // 3秒后自动隐藏
                setTimeout(() => {
                    msgElement.removeClass('show').addClass('hide');
                    setTimeout(() => {
                        msgElement.hide();
                    }, 300);
                }, 3000);
            }, 300);
        }

        // 获取评价状态文本
        function getOrderDiscussIfText(status) {
            const statusMap = {
                '0': '未评价',
                '1': '已评价'
            };
            return statusMap[status] || '未知状态';
        }

        // 获取退款状态文本
        function getRefundStatusText(status) {
            const statusMap = {
                '0': '未退款',
                '1': '退款中',
                '2': '已退款',
                '3':'不同意退款'
            };
            return statusMap[status] || '未知状态';
        }

        // 获取订单数据
        function fetchData() {
            showLoading();

            const params = {
                page: currentPage,
                limit: limit
            };

            if ($('#ordernum').val()) {
                params.ordernum = $('#ordernum').val();
            }

            if ($('#userName').val()) {
                params.userName = $('#userName').val();
            }

            if ($('#orderstatus').val()) {
                params.orderstatus = $('#orderstatus').val();
            }

            $.ajax({
                url: 'http://localhost:8887/ordercake/selectapplyfund',
                type: 'GET',
                data: params,
                success: function(response) {
                    hideLoading();
                    if (response.code == 200) {
                        tableData = response.data.selectapplyfund.list || [];
                        total = response.data.selectapplyfund.total || 0;
                        renderTable();
                        updatePagination();
                    } else {
                        showMessage('error', response.msgerr || '获取数据失败');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '请求失败: ' + error);
                }
            });
        }

        // 渲染表格
        function renderTable() {
            const tbody = $('#orderTable tbody');
            tbody.empty();

            tableData.forEach(function(row) {
                const tr = $(`
                        <tr>
                            <td>${row.orderid}</td>
                            <td>${row.ordernum}</td>
                            <td>${row.userName}</td>
                            <td>¥${Number(row.orderprice).toFixed(2)}</td>
                            <td>${row.orderecount}</td>
                            <td>${getOrderStatusText(row.orderstatus)}</td>
                            <td>${getOrderDiscussIfText(row.orderdiscussif)}</td>
                            <td>
                                <span class="el-tag el-tag--${row.refund == '0' ? 'info' : row.refund == '1' ? 'warning' : 'success'}"
                                    onclick="handleRefundClick(${row.orderid}, '${row.refund}')"
                                    style="cursor: ${row.refund == '1' ? 'pointer' : 'default'}">
                                    ${getRefundStatusText(row.refund)}
                                </span>
                            </td>
                            <td>${row.cakename}</td>
                            <td>${row.ordertime}</td>
                            <td>${row.userreason != null ? row.userreason : ''}</td>
                            <td>${row.shopreply != null ? row.shopreply : ''}</td>
                        </tr>
                    `);

                tbody.append(tr);
            });
        }

        // 分页控制函数
        function prevPage() {
            if (currentPage > 1) {
                currentPage--;
                fetchData();
            }
        }

        function nextPage() {
            if (currentPage * limit < total) {
                currentPage++;
                fetchData();
            }
        }

        function firstPage() {
            if (currentPage > 1) {
                currentPage = 1;
                fetchData();
            }
        }

        function lastPage() {
            if (currentPage * limit < total) {
                currentPage = Math.ceil(total / limit);
                fetchData();
            }
        }

        // 更新分页状态
        function updatePagination() {
            $('#currentPage').text(currentPage);
            $('#totalItems').text(total);

            const prevBtn = $('#prevBtn');
            const nextBtn = $('#nextBtn');
            const firstBtn = $('#firstBtn');
            const lastBtn = $('#lastBtn');

            prevBtn.prop('disabled', currentPage <= 1);
            nextBtn.prop('disabled', currentPage * limit >= total);
            firstBtn.prop('disabled', currentPage <= 1);
            lastBtn.prop('disabled', currentPage * limit >= total);
        }

        // 搜索
        function handleSearch() {
            currentPage = 1;
            fetchData();
        }

        // 重置搜索
        function resetSearch() {
            $('#ordernum').val('');
            $('#userName').val('');
            $('#orderstatus').val('');
            handleSearch();
        }

        // 处理行选择
        function handleRowSelection(checkbox, orderid) {
            if (checkbox.checked) {
                selectedRows.push(orderid);
            } else {
                selectedRows = selectedRows.filter(id => id !== orderid);
            }
            $('#batchToggleBtn').prop('disabled', selectedRows.length == 0);
        }

        // 全选功能
        function toggleSelectAll() {
            const selectAll = $('#selectAll').prop('checked');
            const checkboxes = $('#orderTable tbody input[type="checkbox"]');

            checkboxes.each(function() {
                $(this).prop('checked', selectAll);
                const orderid = parseInt($(this).data('id'));

                if (selectAll) {
                    if (!selectedRows.some(id => id == orderid)) {
                        selectedRows.push(orderid);
                    }
                } else {
                    selectedRows = selectedRows.filter(id => id !== orderid);
                }
            });

            $('#batchToggleBtn').prop('disabled', selectedRows.length == 0);
        }

        // 批量切换状态
        function handleBatchToggle() {
            const orderIds = selectedRows;

            if (orderIds.length == 0) return;

            if (confirm(`确定切换 ${orderIds.length} 个订单的状态吗？`)) {
                showLoading();

                $.ajax({
                    url: 'http://localhost:8887/ordercake/batchUpdateStatus',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        orderIds: orderIds
                    }),
                    success: function(response) {
                        hideLoading();
                        if (response.code == 200) {
                            showMessage('success', '批量切换成功');
                            fetchData();
                            selectedRows = [];
                            $('#selectAll').prop('checked', false);
                        } else {
                            showMessage('error', response.msgerr || '批量切换失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        hideLoading();
                        showMessage('error', '请求失败: ' + error);
                    }
                });
            }
        }

        // 退款相关函数
        function handleRefundClick(orderid, refundStatus) {
            if (refundStatus == '1') { // 仅在退款中状态时允许点击
                openRefundDialog(tableData.find(row => row.orderid == orderid));
            }
        }
        // 打开退款确认弹窗
        function openRefundDialog(row) {
            currentRefundOrder = row;
            isRefuseMode = false; // 重置为非拒绝模式（初始状态）
            $('#refuseReason').hide(); // 隐藏拒绝理由输入框
            $('#refuseBtn').text('不同意退款'); // 重置按钮文本
            $('#agreeRefundBtn').show(); // 显示【同意退款】按钮
            $('#refundDialog').css('display', 'flex');
        }
        // 切换不同意退款模式（点击【不同意退款】按钮时触发）
        function toggleRefuseReason() {
            isRefuseMode = !isRefuseMode;
            const reasonElement = $('#refuseReason');
            const refuseBtn = $('#refuseBtn');
            const agreeRefundBtn = $('#agreeRefundBtn');

            if (isRefuseMode) {
                // 进入【不同意退款】模式：显示输入框，按钮改为【提交理由】
                reasonElement.show();
                refuseBtn.text('提交理由');
                reasonElement.focus();
                agreeRefundBtn.hide(); // 隐藏【同意退款】按钮
            } else {
                // 退出【不同意退款】模式：校验理由并提交
                const reason = reasonElement.val().trim();
                if (!reason) {
                    alert('请输入不同意退款的理由');
                    isRefuseMode = true; // 恢复为拒绝模式（保持输入框显示）
                    return; // 阻止退出，强制填写理由
                }
                // 调用接口提交理由（示例，需替换实际接口逻辑）
                refuseRefund(reason);
                agreeRefundBtn.show(); // 恢复显示【同意退款】按钮
            }
        }

        // 关闭退款确认弹窗（点击右上角×或【取消】时触发）
        function closeRefundDialog() {
            $('#refuseReason').val('').hide(); // 清空并隐藏输入框
            // 判断：若处于【不同意退款模式】且未提交理由，恢复 isRefuseMode = true
            if (isRefuseMode && $('#refuseReason').val().trim() === '') {
                isRefuseMode = true; // 恢复为拒绝模式（重新打开时显示【同意退款】按钮）
            } else {
                isRefuseMode = false; // 正常退出，重置模式
            }
            $('#refundDialog').hide();
            currentRefundOrder = null;
        }


        // 同意退款
        function agreeRefund() {
            if (!currentRefundOrder) return;
            // 调用更新退款状态接口（示例，需替换为实际逻辑）
            updateRefundStatus(currentRefundOrder.orderid, '2');
            closeRefundDialog(); // 关闭弹窗
        }
        // 不同意退款并提交理由
        function refuseRefund(reason) {
            if (!currentRefundOrder) return;
            showLoading();
            // 调用商家回复接口
            $.ajax({
                url: 'http://localhost:8887/ordercake/refundReply',
                type: 'POST',
                data: {
                    shopreply: reason,
                    orderid: currentRefundOrder.orderid
                },
                success: function(response) {
                    hideLoading();
                    if (response > 0) {
                        showMessage('success', '已成功提交不同意退款的理由');
                        // 可以根据业务需求决定是否需要将退款状态改回未退款
                        // updateRefundStatus(currentRefundOrder.orderid, '0');
                        fetchData(); // 刷新数据
                        closeRefundDialog();
                    } else {
                        showMessage('error', '提交失败，请重试');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '请求异常: ' + error);
                }
            });
        }
        // 更新退款状态
        function updateRefundStatus(orderid, refund) {
            showLoading();

            $.ajax({
                url: 'http://localhost:8887/ordercake/updateRefundsStatus',
                type: 'POST',
                data: {
                    orderid: orderid,
                    refund: refund
                },
                success: function(response) {
                    hideLoading();
                    if (response.code == 200) {
                        showMessage('success', '退款状态更新成功');
                        fetchData(); // 刷新数据
                    } else {
                        showMessage('error', response.msgerr || '更新失败');
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    showMessage('error', '请求异常: ' + error);
                }
            });
        }
    }
</script>
</body>
</html>
